﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Diploma.Models;
using Diploma.Validation;

namespace DiplomaWeb.Controllers
{
    public class TasksController : MasterController
    {
        public TasksController(DataManager dataManager) : base(dataManager)
        {
        }

        public ActionResult SetCompletion(Guid taskId, bool? isCompleted)
        {
            
            Task task = DataManager.TasksRepository.GetTask(taskId);
            if((task.PrevCheckPoint != null) && (task.PrevCheckPoint is Task) &&
                !(task.PrevCheckPoint as Task).IsCompleted && !task.IsCompleted){
                    return JavaScript("alert('Необходимо выполнить предыдущее задание:" + task.PrevCheckPoint.Name + "')");
                }
            Guid collRoom = (Guid)DataManager.TasksRepository.GetTask(taskId).CollaborationRoomId;

            Guid studentId = DataManager.StudentsRepository.GetStudentByCollaborationRoom(collRoom).UserId;
            if (task == null)
               throw new Exception();

            if (isCompleted != null)
                DataManager.TasksRepository.SetCompletion(task, isCompleted.Value);
            var list = new List<Task> { task};
            foreach (var t in task.NextCheckPoints.OfType<Task>())
            {
                 Task nextTask = DataManager.TasksRepository.GetTask(t.CheckPointId);
                 list.Add(nextTask);                
            }           
            var var = (from t in list.Where(item => item != null)
                       select new { GlobalTaskId = t.GlobalTaskId, StudentId = studentId, TaskId = t.CheckPointId });
            return Json(var, JsonRequestBehavior.AllowGet);
        }


        [HttpGet]
        public ActionResult Add()
        {
            ViewData["PlaningTypes"] = new SelectList(DataManager.PlaningTypesRepository.GetAllPlaningTypes(),
                                                      "PlaningTypeId", "");
            if (DataManager.PlaningsRepository.GetAllPlaningTypes().Count() != 0)
                return PartialView("~/Views/Lecturers/Tasks/TaskAddControl.ascx");
            else
                return Content("No planing types found. Can not add task");
        }

        [HttpPost]
        public ActionResult Add(Task task, int PlaningTypeId, bool ToAll)
        {
            ValidationErrors = Validator.ValidateTask(task, PlaningTypeId);
            if (ValidationErrors.Count() == 0)
            {
                PlaningType planingType = DataManager.PlaningTypesRepository.GetPlaningType(PlaningTypeId);
                if (planingType == null)
                    throw new Exception();
                CollaborationRoom room =
                    DataManager.CollaborationRoomRepository.GetCollaborationRoom(task.CollaborationRoomId.Value);
                if (room == null)
                    throw new Exception();
                DataManager.TasksRepository.Add(task, planingType, room.Student.StudentsGroup.QualificationLevel, ToAll);
            }

            return Json(ValidationErrors, "text/plain", JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult Edit(Guid id)
        {
            Task task = DataManager.TasksRepository.GetTask(id);
            if (task == null)
                throw new Exception();

            ViewData["PlaningTypes"] = new SelectList(DataManager.PlaningTypesRepository.GetAllPlaningTypes(),
                                                      "PlaningTypeId", "", task.GlobalTask.PlaningTypeId);
            ViewData.Model = task;

            return PartialView("~/Views/Lecturers/Tasks/TaskEditControl.ascx");
        }

        [HttpPost]
        public ActionResult Edit(Task task, int PlaningTypeId)
        {
            ValidationErrors = Validator.ValidateTask(task, PlaningTypeId);
            if (ValidationErrors.Count() == 0)
            {
                PlaningType planingType = DataManager.PlaningTypesRepository.GetPlaningType(PlaningTypeId);
                if (planingType == null)
                    throw new Exception();
                DataManager.TasksRepository.Edit(task, planingType);
            }

            return Json(ValidationErrors, "text/plain", JsonRequestBehavior.AllowGet);
        }

        public ActionResult Delete(Guid id)
        {
            Task task = DataManager.TasksRepository.GetTask(id);
            if (task == null)
                throw new Exception();
            DataManager.TasksRepository.Delete(task);

            return Redirect(Request.UrlReferrer.PathAndQuery);
        }

        public JsonResult ByRoomAndPlaningJSON(Guid roomId, int planingId, string taskDate)
        {
            CollaborationRoom room = DataManager.CollaborationRoomRepository.GetCollaborationRoom(roomId);
            if (room == null)
                throw new Exception();
            PlaningType planingType = DataManager.PlaningTypesRepository.GetPlaningType(planingId);
            if (planingType == null)
                throw new Exception();
            DateTime? date = null;
            DateTime tempdate;
            if (DateTime.TryParse(taskDate, out tempdate))
            {
                tempdate = DateTime.Parse(taskDate);
                date = tempdate;
            }

            IEnumerable<Task> v = DataManager.TasksRepository.GetTasksWithDateLower(room, planingType, date);

            return Json(from c in v
                        select new {id = c.CheckPointId, name = c.Name, date = c.StartDate.ToString()},
                        JsonRequestBehavior.AllowGet);
        }
    }
}